package Leo.utils;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {


    //--------------------GET 请求-----------------------
    public static String getRequest(String url, Map<String, String> params) throws Exception {
        if (StringUtils.isBlank(url)) {
            throw new Exception();
        }
        StringBuilder sb = new StringBuilder();
        String strUrl = url;
        sb.append(url);
        if (params != null && params.size() > 0) {
            sb.append("?");
            params.forEach((s, s2) -> {
                sb.append(s).append("=").append(s2).append("&");
            });
            strUrl = sb.substring(0, sb.length() - 1);
        }
        return getRequest(strUrl);
    }

    public static String getRequest(String url, String params) throws IOException {
        return getRequest(url + "?" + params);
    }

    public static String getRequest(String url) throws IOException {
        //开启链接
        URLConnection connection = getConnection(url);
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> map = connection.getHeaderFields();
        // 定义 BufferedReader输入流来读取URL的响应
        String response = readResponse(connection);
        return response;
    }

    //--------------------POST 请求-----------------------

    public static String postRequest(String url, Map<String, String> params) throws IOException {
        StringBuilder sb = new StringBuilder();
        String param = "";
        if (params != null && params.size() > 0) {
            params.forEach((s, s2) -> {
                sb.append(s).append("=").append(s2).append("&");
            });
            param = sb.substring(0, sb.length() - 1);
        }
        return postRequest(url, param);
    }

    public static String postRequest(String url, String param) throws IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        URLConnection conn = getConnection(url);
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        OutputStream outputStream = conn.getOutputStream();
        out = new PrintWriter(outputStream);
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        String response = readResponse(conn);
        out.close();
        outputStream.close();
        return response;
    }

    //-------------------私有方法-----------------

    /**
     * 获取http 链接
     *
     * @param url
     * @return
     * @throws IOException
     */
    private static URLConnection getConnection(String url) throws IOException {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        return conn;
    }

    /**
     * 读取返回信息
     *
     * @param connection
     * @return
     * @throws IOException
     */
    private static String readResponse(URLConnection connection) throws IOException {
        StringBuilder result = new StringBuilder();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader in = new BufferedReader(inputStreamReader);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line).append("\n");
        }
        in.close();
        inputStreamReader.close();
        inputStream.close();
        return result.toString();
    }

    /**
     * http请求get,post整合方式
     * 使用httpclient发送请求,JSONObject作为post请求的参数,方便一些以json对象作为参数和返回对象的请求方法调用
     * @param url
     * @param jsonParam post参数(JSONObject类型)
     * @param requestMethod GET/POST
     * @return JSONObject对象
     * @throws Exception
     */
//    public static JSONObject httpRequest(String url, JSONObject jsonParam, String requestMethod) throws Exception {
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpGet get = null;
//        HttpPost post = null;
//        JSONObject jsonObject = null;
//        CloseableHttpResponse response = null;
//        try {
//            if ("GET".equalsIgnoreCase(requestMethod)) {
//                get = new HttpGet(url);
//                response = httpclient.execute(get);
//            } else if ("POST".equalsIgnoreCase(requestMethod)) {
//                post = new HttpPost(url);
//                //设置参数
//                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
//                entity.setContentEncoding("UTF-8");
//                entity.setContentType("application/json");
//                post.setEntity(entity);
//                response = httpclient.execute(post);
//            }
//            HttpEntity responseEntity = response.getEntity();
//            String responseContent = EntityUtils.toString(responseEntity, "UTF-8");
//            jsonObject = new JSONObject(responseContent);
//        }catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            // 关闭连接,释放资源
//            try {
//                response.close();
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return jsonObject;
//    }
}
